package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.OrderConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "PayOrderConsumer",//消费者组名
        topic = OrderConstants.TOPIC_ORDER_MESSAGE_TRANSACTION,
        selectorExpression = OrderConstants.TAGS_ORDER_MESSAGE_TRANSACTION
)
public class PayOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService iPayOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String message = new String(body, Constants.UTF8);
            CourseOrder courseOrder = JSON.parseObject(message, CourseOrder.class);
            //保存支付单
            System.err.println(courseOrder);
            savePayOrder(courseOrder);
        } catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private void savePayOrder(CourseOrder courseOrder) {
        PayOrder payOrder = new PayOrder();
        payOrder.setCreateTime(new Date());
        payOrder.setAmount(courseOrder.getPayAmount());
        payOrder.setPayType(courseOrder.getPayType());

        List<Long> courseIds = courseOrder.getCourseIds();
        String collect = courseIds.stream().map(id -> id.toString()).collect(Collectors.joining(","));
        payOrder.setRelationId(collect);
        payOrder.setOrderNo(courseOrder.getOrderNo());
        payOrder.setUserId(courseOrder.getUserId());
//            payOrder.setExtParams(); //todo 目前用不到
        payOrder.setSubject(courseOrder.getTitle());
        payOrder.setPayStatus(courseOrder.getStatusOrder());
        iPayOrderService.save(payOrder);
    }
}
